import { ApprovalType, FormField } from '../../types/index';
import { getApprovalType, createApproval } from '../../services/mockData';

Page({
    data: {
        type: 0,
        typeName: '',
        formFields: [] as FormField[],
        formData: {} as Record<string, any>
    },

    async onLoad(options: any) {
        const type = parseInt(options.type || '0');
        const approvalType = await getApprovalType(type);
        if (approvalType) {
            this.setData({
                type,
                typeName: approvalType.name,
                formFields: approvalType.fields
            });
            wx.setNavigationBarTitle({
                title: approvalType.name
            });
        }
    },

    onFieldChange(e: any) {
        const { key } = e.currentTarget.dataset;
        const value = e.detail.value;
        this.setData({
            [`formData.${key}`]: value
        });
    },

    async submitApproval() {
        const { formData, formFields, type } = this.data;
        
        // 验证必填字段
        const missingFields = formFields
            .filter(field => field.required && !formData[field.key])
            .map(field => field.label);

        if (missingFields.length > 0) {
            wx.showToast({
                title: `请填写${missingFields.join('、')}`,
                icon: 'none'
            });
            return;
        }

        const result = await createApproval(formData, type);
        if (result) {
            wx.showToast({
                title: '提交成功',
                icon: 'success',
                success: () => {
                    setTimeout(() => {
                        wx.switchTab({
                            url: '/pages/approvalList/approvalList'
                        });
                    }, 1500);
                }
            });
        }
    },

    goBack() {
        wx.navigateBack();
    }
}); 